//本地存储 localstore 名称
const storeFlagName = "unionSearchFlag";
const storeName = "siteStore";
//无任何勾选时的默认访问地址
const defSite = "https://www.baidu.com/s?wd={s}";
//本地存储 内容
const siteStore = window.localStorage.getItem(storeName);
//layui form对象
const form = layui.form;

console.log("初始化取值flag : " + window.localStorage.getItem(storeFlagName));
let unionSearchFlag = window.localStorage.getItem(storeFlagName) === "true";
console.log("当前flag值 : " + unionSearchFlag);
$(function () {
    /** 回显选择框 */
    if (siteStore && siteStore.length > 0) {
        siteStore.split(",").forEach(t => $(":input[name='site'][value='" + t + "']").prop("checked", true));
        form.render();
    }

    if (!unionSearchFlag) {
        $(":input[name='method']").prop("checked", false);
        form.render();
    }

    /** 切换联合搜索开关 */
    form.on('switch(search-method)', function (data) {
        unionSearchFlag = data.elem.checked;
        console.log("更新 flag : " + unionSearchFlag);
        window.localStorage.setItem(storeFlagName, unionSearchFlag);
        if (!unionSearchFlag) {//关闭联合搜索
            const siteArr = $(":input[name='site']:checked");
            if (siteArr.length > 1) {//选择了多个
                $(":input[name='site']:checked").prop("checked", false).eq(0).prop("checked", true);
                form.render();
                saveSite();
            }
        }
    });

    /** 点击搜索引擎时更新存储 */
    form.on('checkbox(mysite)', function (data) {
        console.log(unionSearchFlag);
        if (!unionSearchFlag) {//关闭联合搜索
            $(":input[name='site']:checked").prop("checked", false);
            $(":input[name='site'][value='" + data.value + "']").prop("checked", true);
            form.render();
        }
        saveSite();
    });

    /** 执行搜索 */
    $(".search").click(search);
    $("#content").keydown(function (e) {
        if (e.key === "Enter") {
            search();
        }
    });
});

/** 保存站点数据 */
function saveSite() {
    const siteArr = $(":input[name='site']:checked");
    let siteStr = "";
    siteArr.each(function (i) {
        if (i !== 0) {
            siteStr += ",";
        }
        siteStr += $(this).val();
    });
    window.localStorage.setItem(storeName, siteStr);
}

/** 搜索业务方法 */
function search() {
    let content = $("#content").val();
    const siteArr = $(":checkbox[name='site']:checked");
    if (!siteArr || siteArr.length === 0) {
        window.location.href = defSite.replace("{s}", content);
    }

    siteArr.each(function (i) {
        if (i < siteArr.length - 1) {
            window.open($(this).val().replace("{s}", content), "_blank");
        } else {
            window.location.href = $(this).val().replace("{s}", content);
        }
    });
}